package tech.aistar.day10.syn;

/**
 * 本类用来演示: 同步代码块
 *
 * @author: success
 * @date: 2022/8/1 1:54 下午
 */
public class SynBlockDemo implements Runnable{
   // private static Object obj = new Object();
    private Object obj2 = new Object();

    @Override
    public void run() {
        test();
    }
    public void test(){
        //不需要同步的代码.

        //括号中可以写这个类的class实例 - 一个类在jvm中的class实例永远只有1个.
        //"类锁"
        //synchronized (SynBlockDemo.class) { // 推荐
       // synchronized (obj) { //"类锁 = obj - static"
        //synchronized (obj2) { // "对象锁 = obj2 - 非static"
        synchronized (this) { // "对象锁
            //在某个时刻,只能由一个线程进入.
            System.out.println(Thread.currentThread().getName() + ":enter~");
            try {
                //故意睡一秒,"嘚瑟一会"
                Thread.sleep(1000);//让出cpu.但是不会释放锁
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ":leave~");
        }
        //不需要同步的代码.
    }
}
class SynBlockDemoTest{
    //三个线程 main,t1,t2
    public static void main(String[] args) {
        Runnable r1 = new SynBlockDemo();
        Runnable r2 = new SynBlockDemo();

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r1);

        t1.start();
        t2.start();

        System.out.println("===main===:"+Thread.currentThread().getName());
    }
}